package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.ParseException
import java.text.SimpleDateFormat

/**
 *
 * @Title: waterOffSms 智慧停水数据同步接口--外部接口
 * @author: cheih* @date 2021-03-05 10:28:00
 *
 */

public class waterOffSms implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(waterOffSms.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        long startTime = System.currentTimeMillis();

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";
        String wateroffplantype = "";

        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def timestamp = KHUtil.GetJV(inObject, "timestamp");//时间戳
            def sign = KHUtil.GetJV(inObject, "sign");//密钥

            log.debug("解析信息-" + " timestamp: " + timestamp + " sign: " + sign);
            String reJson = null;
            long endTime = 0;

            String apiid = "waterOff";
            String apikey = "55bd38420d354822bdb789284fac4ab3";

            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + apikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);
            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!sign.equals(signafter)) {
                log.debug("signafter不存在");
                endTime = System.currentTimeMillis();
                outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            } else {

                wateroffplantype = KHUtil.GetJV(inObject, "wateroffplantype");// normal 正常 change 改期 delay 延期

                if (wateroffplantype == "change") {
                    // 改期（原停水编号，类型，取消原因） 改期仅需要关闭现有批次即可 综合调度系统会重新推送批次
                    String wateroffoldsmsguid = KHUtil.GetJV(inObject, "wateroffoldsmsguid");
                    String wateroffchangetype = KHUtil.GetJV(inObject, "wateroffchangetype");
                    String wateroffchangereason = KHUtil.GetJV(inObject, "wateroffchangereason");
                    String content = KHUtil.GetJV(inObject, "content");//停水短信内容

                    //非空校验
                    String dealMessage = KHUtil.isNullMSG("wateroffoldsmsguid", wateroffoldsmsguid) + KHUtil.isNullMSG("wateroffchangetype", wateroffchangetype) + KHUtil.isNullMSG("wateroffchangereason", wateroffchangereason) + KHUtil.isNullMSG("content", content);

                    if (!KHUtil.isNull(dealMessage)) {
                        endTime = System.currentTimeMillis();
                        outData = "{\"resultcode\":\"0\",\"resultmessage\":\"调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    } else {
                        log.debug("入参：wateroffsmsguid" + wateroffoldsmsguid + ", wateroffchangetype:" + wateroffchangetype + ", wateroffchangereason:" + wateroffchangereason);
                        //新增SMS
                        outData = changeSMS(eliteBean, wateroffoldsmsguid, wateroffchangetype, wateroffchangereason, content);
                    }

                } else if (wateroffplantype == "delay") {
                    // 延期（原停水编号，延期后供水日期，延期原因）
                    String wateroffoldsmsguid = KHUtil.GetJV(inObject, "wateroffoldsmsguid");
                    String wateroffdelaytime = KHUtil.GetJV(inObject, "wateroffdelaytime");
                    String wateroffdelayreason = KHUtil.GetJV(inObject, "wateroffdelayreason");
                    String content = KHUtil.GetJV(inObject, "content");//停水短信内容

                    //非空校验
                    String dealMessage = KHUtil.isNullMSG("wateroffoldsmsguid", wateroffoldsmsguid) + KHUtil.isNullMSG("wateroffdelaytime", wateroffdelaytime) + KHUtil.isNullMSG("wateroffdelayreason", wateroffdelayreason);

                    if (!KHUtil.isNull(dealMessage)) {
                        endTime = System.currentTimeMillis();
                        outData = "{\"resultcode\":\"0\",\"resultmessage\":\"调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    } else {
                        log.debug("入参：wateroffsmsguid" + wateroffoldsmsguid + ", wateroffdelaytime:" + wateroffdelaytime + ", wateroffdelayreason:" + wateroffdelayreason);
                        //新增SMS
                        outData = delaySMS(eliteBean, wateroffoldsmsguid, wateroffdelaytime, wateroffdelayreason, content);
                    }

                } else {

                    String wateroffsmsguid = KHUtil.GetJV(inObject, "wateroffsmsguid");//停水批次编号
                    String wateroffoldsmsguid = KHUtil.GetJV(inObject, "wateroffoldsmsguid");//原停水批次编号
                    String wateroffsmsname = KHUtil.GetJV(inObject, "wateroffsmsname");//停水批次名称
                    String cutoffwater = KHUtil.GetJV(inObject, "cutoffwater");//停水原因
                    String content = KHUtil.GetJV(inObject, "content");//停水短信内容
                    String waterofftime = KHUtil.GetJV(inObject, "waterofftime");//关阀时间
                    String waterontime = KHUtil.GetJV(inObject, "waterontime");//恢复通水时间
                    String arr_data = KHUtil.GetJV(inObject, "data");//停水名单List

                    // 判断是否是取消
                    if (KHUtil.isNull(wateroffplantype) && !KHUtil.isNull(content) && (KHUtil.isNull(arr_data) || arr_data == "[]")) {
                        wateroffplantype = "cancel";
                        //非空校验
                        String dealMessage = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffsmsname", wateroffsmsname) + KHUtil.isNullMSG("content", content) + KHUtil.isNullMSG("cutoffwater", cutoffwater);

                        if (!KHUtil.isNull(dealMessage)) {
                            endTime = System.currentTimeMillis();
                            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"取消调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                        } else {
                            log.debug("取消调用入参：wateroffsmsguid" + wateroffsmsguid + ", wateroffsmsname:" + wateroffsmsname + ", content:" + content + ", waterofftime:" + waterofftime + ", waterontime:" + waterontime + ", arr_data:" + arr_data + ", cutoffwater:" + cutoffwater);
                            //新增SMS
                            outData = cancelSMS(eliteBean, wateroffsmsguid, wateroffsmsname, content, cutoffwater);
                        }
                    } else {
                        wateroffplantype = "add";
                        //非空校验
                        String dealMessage = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffsmsname", wateroffsmsname) + KHUtil.isNullMSG("cutoffwater", cutoffwater) + KHUtil.isNullMSG("content", content) + KHUtil.isNullMSG("waterofftime", waterofftime) + KHUtil.isNullMSG("waterontime", waterontime) + KHUtil.isNullMSG("arr_data", arr_data);

                        if (!KHUtil.isNull(dealMessage)) {
                            endTime = System.currentTimeMillis();
                            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"新增调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                        } else {
                            log.debug("新增调用入参：wateroffsmsguid" + wateroffsmsguid + ", wateroffsmsname:" + wateroffsmsname + ", content:" + content + ", waterofftime:" + waterofftime + ", waterontime:" + waterontime + ", arr_data:" + arr_data);
                            //新增SMS
                            outData = SMSAdd(eliteBean, wateroffsmsguid, wateroffsmsname, content, waterofftime, waterontime, cutoffwater, arr_data, wateroffoldsmsguid);
                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "智慧停水[短信]", "waterOffSms", inData, outData, (System.currentTimeMillis() - startTime).toString(), wateroffplantype);
        }

        log.debug("短信数据接入处理完成返回结果:" + outData);

        return outData;
    }

    // 短信新建处理
    public static String SMSAdd(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String content, String waterofftime, String waterontime, String cutoffwater, String inJson, String wateroffoldsmsguid) {

        long startTime = System.currentTimeMillis();
        log.debug("短信处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {
            //查询现有当前短信批次是否存在
            def getSelectSQL = eliteBean.chaxun_sql("select count(*) as count from waterOffSmsbatch where 1=1 and status!=2 and wateroffsmsguid= '" + wateroffsmsguid + "' ", "dataSource");
            if (getSelectSQL.size() > 0) {
                def count = getSelectSQL.get(0).get("count");
                if (count > 0) {//存在则废弃之前的批次
                    String[] abandondata = new String[2];
                    //将还未发送成功的批次更新为废弃
                    abandondata[0] = "update waterOffSmsbatch set status=3,Ismain = 0,suspenddate=GETDATE() where 1=1 and status!=2 and  wateroffsmsguid=  '" + wateroffsmsguid + "'";
                    //废弃还未同步的短信
                    abandondata[1] = "update DocumentOut set status=2 where 1=1 and Passflag is null and  sub_doctype=  '" + wateroffsmsguid + "'";

                    log.debug("当前短信批次已经存在执行结果SQL:" + abandondata.toString());
                    def abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                    log.debug("当前短信批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                }
            }
            String sms_guid = UUID.randomUUID().toString();

            eliteBean.update("Update waterOffSmsbatch Set Ismain = 0 Where Wateroffsmsguid = '" + wateroffsmsguid + "'", "dataSource");
            def batchresult = eliteBean.update("INSERT INTO waterOffSmsbatch([wateroffsmsguid], [wateroffsmsname], [content], [waterofftime], [waterontime], [createdate],[sms_guid],[status],[cutoffwater],[wateroffoldsmsguid],ismain) VALUES ('" + wateroffsmsguid + "', '" + wateroffsmsname + "', '" + content + "', '" + waterofftime + "','" + waterontime + "',GETDATE(),'" + sms_guid + "',0,'" + cutoffwater + "','" + wateroffoldsmsguid + "',1)", "dataSource");
            log.debug("batchresult:" + batchresult.toString());
            log.debug("当前批次新建结果SQL结果:" + batchresult.toString());

            JSONArray arrJsonArray = new JSONArray(inJson);
            int arrInt = arrJsonArray.length();
            log.debug("接入List数量:" + arrInt);

            JSONArray resArray = new JSONArray();

            for (int i = 0; i < arrInt; i++) {

                JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
                String ani = KHUtil.GetJV(arrSmsJson, "ani"); //手机号码
                String usercode = KHUtil.GetJV(arrSmsJson, "usercode"); //用户编号

                JSONObject dealResult = new JSONObject();
                dealResult.put("ani", ani);
                dealResult.put("usercode", usercode);

                //处理结果字段dealResult 1成功 其他失败，处理原则：新增是手机不能存在，更新是手机必须存在
                if (KHUtil.isNull(ani)) {
                    dealResult.put("code", 0);
                    dealResult.put("message", KHUtil.isNullMSG("ani", ani));

                } else {
                    try {//停水通知短信提前24小时发送，这里需要微调一下，超过晚上9点就不能发了，设置为提前（21:00）发送

                        //转换时间获取时分秒
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String str = waterofftime;
                        Date d = formatter.parse(str);
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                        String date = format.format(d);
                        log.debug("获得时分秒date：" + date);

                        String timeString = date;
                        def flag = checkTimeIsBetween(timeString);//1在0不在

                        String[] data = new String[2];
                        data[0] = "INSERT INTO DOCUMENTOUT ( DOCUMENTOUT_GUID, DOCTYPE, STATUS, TRIALCOUNT, TRIALCOUNTLIMIT, DOCUMENTPATH, HANDLEBY_ID, HANDLEGROUP_ID, CUSTOMER_GUID, CREATEDBY, CREATEDDATE, EXPECTEDSTARTDATE, DOCUMENTTO, stringfield1,sub_doctype,sms_guid,ucisid) select newid(),3,3,0,5,'" + content + "','SELITE','SYSTEM','','SELITE',GETDATE(),case when '" + flag + "'=0 then ((CONVERT(varchar(12) ,dateadd(hour,-24,'" + waterofftime + "'), 111 ))+' 21:00:00') when '" + flag + "'=1 then  dateadd(hour,-24,'" + waterofftime + "') end ,'" + ani + "','智慧停水发送','" + wateroffsmsguid + "','" + sms_guid + "','" + usercode + "' ";
                        data[1] = "update waterOffSmsbatch set count=count+1 where wateroffsmsguid=  '" + wateroffsmsguid + "' and sms_guid='" + sms_guid + "'";

                        log.debug("当前短信号码执行insert结果SQL:" + data.toString());
                        def dataresult = eliteBean.updateBatch(data, "dataSource");
                        log.debug("当前短信号码执行insert结果SQL结果:" + dataresult.toString());

                        dealResult.put("code", 1);
                        dealResult.put("message", "当前号码处理成功");

                    } catch (Exception e) {
                        dealResult.put("code", 0);
                        dealResult.put("message", "当前短信号码已经存在执行更新结果SQL异常:" + e.getMessage());
                        log.error("当前短信号码已经存在执行更新结果SQL异常:" + e.getMessage());
                    }
                    log.debug("当前短信号码ID:" + ani + " 处理结果Code:" + dealResult + " 处理结果Message:" + dealResult.toString());
                    resArray.put(dealResult);
                }
            }

            def statusresult = eliteBean.update("update waterOffSmsbatch set status=1,modifydate=GETDATE() where wateroffsmsguid=  '" + wateroffsmsguid + "' and sms_guid='" + sms_guid + "'", "dataSource");
            log.debug("当前批次同步完成 Status更新:" + statusresult.toString());

            //生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + ",批次名称：" + wateroffsmsname + "处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";


        } catch (JSONException e) {
            endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + ",批次名称：" + wateroffsmsname + "处理失败(" + e.getMessage() + "),调用处理时长(毫秒):" + (endTime - startTime) + "\"}";
        }

        return reJson;
    }

    // 短信改期处理
    public static String changeSMS(EliteBean eliteBean, String wateroffoldsmsguid, String wateroffchangetype, String wateroffchangereason, String content) {

        long startTime = System.currentTimeMillis();
        log.debug("短信改期处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Wateroffsmsbatch Where Wateroffsmsguid = '" + wateroffoldsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {

                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                // 将批次改为改期
                abandondata[0] = '''Update Wateroffsmsbatch
                                       Set Status       = 5,
                                           Ismain       = 0,
                                           Suspenddate  = Getdate(),
                                           Changetype   = \'''' + wateroffchangetype + '''\',
                                           Changereason = \'''' + wateroffchangereason + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                //废弃还未同步的短信
                abandondata[1] = '''Update Documentout Set Status = -5 Where 1 = 1 And Passflag Is Null And Status = 3 And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 新生成主任务
                abandondata[2] = '''Insert Into Wateroffsmsbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Content,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Wateroffoldsmsguid,
                                           Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 \'''' + content + '''\',
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 Wateroffoldsmsguid,
                                                 1, Count
                                            From Wateroffsmsbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Documentout
                                          (Documentout_Guid,
                                           Doctype,
                                           Status,
                                           Trialcount,
                                           Trialcountlimit,
                                           Documentpath,
                                           Handleby_Id,
                                           Handlegroup_Id,
                                           Createdby,
                                           Createddate,
                                           Expectedstartdate,
                                           Documentto,
                                           Stringfield1,
                                           Sub_Doctype,
                                           Sms_Guid,
                                           Ucisid)
                                          Select Newid(),* From (Select Distinct
                                                 3 AS Doctype,
                                                 3 AS Status,
                                                 0 AS Trialcount,
                                                 5 AS Trialcountlimit,
                                                 \'''' + content + '''\' AS Documentpath,
                                                 'SELITE' AS Handleby_Id,
                                                 'SYSTEM' AS Handlegroup_Id,
                                                 'SELITE' AS Createdby,
                                                 Getdate() AS Createddate,
                                                 Getdate() AS Expectedstartdate,
                                                 Documentto AS Documentto,
                                                 '智慧停水发送' AS Stringfield1,
                                                 Sub_Doctype,
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 Ucisid
                                            From Documentout
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前短信批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前短信批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffoldsmsguid + " 改期处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffoldsmsguid + " 改期处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";

            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffoldsmsguid + " 改期处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 短信延期处理
    public static String delaySMS(EliteBean eliteBean, String wateroffoldsmsguid, String wateroffdelaytime, String wateroffdelayreason, String content) {

        long startTime = System.currentTimeMillis();
        log.debug("短信延期处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Wateroffsmsbatch Where Wateroffsmsguid = '" + wateroffoldsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {

                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];

                //将还未发送成功的批次更新为废弃
                abandondata[0] = '''Update Wateroffsmsbatch
                                       Set Status       = 6,
                                           Ismain       = 0,
                                           Suspenddate  = Getdate(),
                                           Delaytime   = \'''' + wateroffdelaytime + '''\',
                                           Delayreason = \'''' + wateroffdelayreason + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                //废弃还未同步的短信
                abandondata[1] = '''Update Documentout Set Status = -6 Where 1 = 1 And Passflag Is Null And Status = 3 And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 新生成主任务
                abandondata[2] = '''Insert Into Wateroffsmsbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Content,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Wateroffoldsmsguid,
                                           Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 \'''' + content + '''\',
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 Wateroffoldsmsguid,
                                                 1, Count
                                            From Wateroffsmsbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Documentout
                                          (Documentout_Guid,
                                           Doctype,
                                           Status,
                                           Trialcount,
                                           Trialcountlimit,
                                           Documentpath,
                                           Handleby_Id,
                                           Handlegroup_Id,
                                           Createdby,
                                           Createddate,
                                           Expectedstartdate,
                                           Documentto,
                                           Stringfield1,
                                           Sub_Doctype,
                                           Sms_Guid,
                                           Ucisid)
                                          Select Newid(),* From (Select Distinct
                                                 3 AS Doctype,
                                                 3 AS Status,
                                                 0 AS Trialcount,
                                                 5 AS Trialcountlimit,
                                                 \'''' + content + '''\' AS Documentpath,
                                                 'SELITE' AS Handleby_Id,
                                                 'SYSTEM' AS Handlegroup_Id,
                                                 'SELITE' AS Createdby,
                                                 Getdate() AS Createddate,
                                                 Getdate() AS Expectedstartdate,
                                                 Documentto AS Documentto,
                                                 '智慧停水发送' AS Stringfield1,
                                                 Sub_Doctype,
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 Ucisid
                                            From Documentout
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前短信批次已经存在执行结果SQL:" + abandondata.toString());

                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前短信批次已经存在执行结果SQL结果:" + abandondataresult.toString());
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffoldsmsguid + " 延期处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";

            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffoldsmsguid + " 延期处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";

            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffoldsmsguid + " 延期处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 短信取消处理
    public static String cancelSMS(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String content, String cutoffwater) {

        long startTime = System.currentTimeMillis();
        log.debug("短信取消处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Wateroffsmsbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {

                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];

                //将还未发送成功的批次更新为废弃
                abandondata[0] = '''Update Wateroffsmsbatch
                                       Set Status       = 4,
                                           Ismain       = 0,
                                           Suspenddate  = Getdate(),
                                           Canceltime   = Getdate(),
                                           Cancelreason = \'''' + cutoffwater + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                //废弃还未同步的短信
                abandondata[1] = '''Update Documentout Set Status = -4 Where 1 = 1 And Passflag Is Null And Status = 3 And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 新生成主任务
                abandondata[2] = '''Insert Into Wateroffsmsbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Content,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Wateroffoldsmsguid,
                                           Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 \'''' + content + '''\',
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 Wateroffoldsmsguid,
                                                 1, Count
                                            From Wateroffsmsbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Documentout
                                          (Documentout_Guid,
                                           Doctype,
                                           Status,
                                           Trialcount,
                                           Trialcountlimit,
                                           Documentpath,
                                           Handleby_Id,
                                           Handlegroup_Id,
                                           Createdby,
                                           Createddate,
                                           Expectedstartdate,
                                           Documentto,
                                           Stringfield1,
                                           Sub_Doctype,
                                           Sms_Guid,
                                           Ucisid)
                                          Select Newid(),* From (Select Distinct
                                                 3 AS Doctype,
                                                 3 AS Status,
                                                 0 AS Trialcount,
                                                 5 AS Trialcountlimit,
                                                 \'''' + content + '''\' AS Documentpath,
                                                 'SELITE' AS Handleby_Id,
                                                 'SYSTEM' AS Handlegroup_Id,
                                                 'SELITE' AS Createdby,
                                                 Getdate() AS Createddate,
                                                 Getdate() AS Expectedstartdate,
                                                 Documentto AS Documentto,
                                                 '智慧停水发送' AS Stringfield1,
                                                 Sub_Doctype,
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 Ucisid
                                            From Documentout
                                           Where Sub_Doctype = \'''' + wateroffsmsguid + '''\') R1''';

                log.debug("当前短信批次已经存在执行结果SQL:" + abandondata.toString());

                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前短信批次已经存在执行结果SQL结果:" + abandondataresult.toString());
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";

            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";

            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    //判断时间是否在9点到21点时间段 1在 0 不在
    public static String checkTimeIsBetween(String timeString) throws ParseException {
        String format = "HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);

        Date timeDate1 = simpleDateFormat.parse(timeString);

        Date startTime = simpleDateFormat.parse("09:00:00");
        Date endTime = simpleDateFormat.parse("21:00:00");

        String dateresult;
        if (timeDate1.before(startTime) || timeDate1.after(endTime)) {//此时间不 在当天9点至21点之间
            dateresult = "0";
        } else {//此时间在当天9点至21点之间
            dateresult = "1";
        }
        return dateresult;
    }

}
